//
//  FileStorageManager.swift
//  SwiftApiTrans
//
//  Created by 袁炳生 on 2024/8/1.
//

import UIKit

open class FileStorageManager: NSObject {
    open class var `default`: FileStorageManager {
        get {
            return FileStorageManager()
        }
    }
    public func saveFile(dirName: String, data: Data) -> String {
        let fm = FileManager.default
        var dpath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        if let path = dpath {
            if !fm.fileExists(atPath: path) {
                do {
                    try fm.createDirectory(atPath: path, withIntermediateDirectories: true)
                    let filePath = "\(path)/\(dirName)"
                    let b = fm.createFile(atPath: filePath, contents: data)
                    if (!b) {
                        print("文件存储失败")
                    } else {
                        print("文件存储成功")
                        return filePath
                    }
                } catch {
                    print("目录创建失败")
                }
            } else {
                do {
                    try fm.createDirectory(atPath: path, withIntermediateDirectories: true)
                    let filePath = "\(path)/\(dirName)"
                    let b = fm.createFile(atPath: filePath, contents: data)
                    if (!b) {
                        print("文件存储失败")
                    } else {
                        print("文件存储成功")
                        return filePath
                    }
                } catch {
                    print("目录创建失败")
                }
            }
        } else {
            print("路径获取失败")
        }
        return ""
    }
    
}
